package org.monkey.request.plugin.advisor;

import cn.hutool.core.util.StrUtil;
import javax.annotation.PostConstruct;
import org.aopalliance.aop.Advice;
import org.monkey.request.plugin.service.RequestLogHandleContext;
import org.springframework.aop.Pointcut;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.framework.adapter.AdvisorAdapterRegistry;
import org.springframework.aop.framework.adapter.GlobalAdvisorAdapterRegistry;
import org.springframework.aop.support.AbstractPointcutAdvisor;

public class RequestLogAdvisor extends AbstractPointcutAdvisor {
  private RequestLogHandleContext requestLogHandleContext;
  private String  express;
  private Pointcut pointcut;
  private Advice advice;
  /**
   * register AdvisorAdapter firstly!
   */
  @PostConstruct
  public void init() {
    AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
    registry.registerAdvisorAdapter(new ResLogAdvisorAdapter());
  }

  public RequestLogAdvisor(RequestLogHandleContext requestLogHandleContext, String express) {
    this.requestLogHandleContext = requestLogHandleContext;
    this.express = express;
    // 拦截上方法标有@ResLog此注解的任意方法
    String pointcutExpression = "@annotation(org.monkey.request.plugin.entity.ResLog)";
    if(StrUtil.isNotBlank(express)){
      pointcutExpression= pointcutExpression +"||"+express;
    }
    AspectJExpressionPointcut cut = new AspectJExpressionPointcut();
    cut.setExpression(pointcutExpression);
    this.pointcut = cut;
    this.advice=new RequestLogAdvice(requestLogHandleContext);
  }

  @Override
  public Pointcut getPointcut() {
    return pointcut;
  }

  @Override
  public Advice getAdvice() {
    return advice;
  }

  @Override
  public boolean isPerInstance() {
    return false;
  }
}
